package com.example.crm.servlet;

import com.example.crm.pojo.Customer;
import com.example.crm.service.ICustomerService;
import com.example.crm.service.impl.CustomerServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

@WebServlet("/customer/addcheck")
public class CustomerAddCheckServlet extends HttpServlet
{
    ICustomerService customerService;// = new CustomerServiceImpl();


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        customerService = (ICustomerService)applicationContext.getBean("customerService");


        req.setCharacterEncoding("UTF-8");
        System.out.println("名称:"+req.getParameter("name"));

        // 1. 接收参数
        Customer c = new Customer();
        System.out.println(req.getParameterMap());
        try {
            BeanUtils.populate(c,req.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        // 2. 调用service
        customerService.add(c);

        // 3. 跳转
        resp.sendRedirect("/customer/list");
    }
}
